<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: 16 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px;">
        <el-table :data="list" border :default-sort="{ prop: 'timeOfEntry', order: 'descending' }">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="用户头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width:100%" @click="showQrCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="聘用形式">
            <template #default="{row}">
              {{ formatHireType(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="assignRoles(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 3, 4, 5]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        @close="hClose"
      >
        <add-or-edit ref="emp" @success="hSuccess" />
      </el-dialog>
      <el-dialog title="分配角色" :visible.sync="assignDialog">
        <assignRole
          v-if="assignDialog"
          :user-id="userId"
          @success="assignDialog = false"
        />
      </el-dialog>
      <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import employeesEnum from '@/constant/employees'
import addOrEdit from './empDialog.vue'
import { transZhExcel } from '@/utils'
import assignRole from './components/assign-role.vue'
import QrCode from 'qrcode'
// const hireType = {}
// employeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })

const hireType = employeesEnum.hireType.reduce((arc, item) => {
  arc[item.id] = item.value
  return arc
}, {})
export default {
  components: {
    addOrEdit,
    assignRole
  },
  data() {
    return {
      list: [],
      userId: '',
      showDialog: false,
      assignDialog: false,
      showCodeDialog: false, // 二维码查看弹框显示控制变量
      total: 0,
      page: 1,
      size: 5
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    async  loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    },
    exportExcel() {
      const { tHeader, result } = transZhExcel(this.list)
      console.log(tHeader, result)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: tHeader, // 表头 必填
          data: result, // 具体数据 必填
          filename: 'IHRM', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    showQrCode(url) {
      // url存在的情况下 才弹出层
      if (url) {
        this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    // 关闭
    hClose() {
      this.$refs.emp.resetForm()
    },
    hSuccess() {
      // 新增优化
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.showDialog = false
      this.loadEmployeeList()
    },
    // 分配角色
    assignRoles(id) {
      this.userId = id
      this.assignDialog = true
    },
    hDel(id) {
      this.$confirm('你确定删除吗').then(async() => {
        const res = await delEmployee(id)
        console.log(res)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        if (res.code === 10000) {
          this.loadEmployeeList()
        }
      }).catch(error => {
        console.log(error)
      })
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployeeList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeeList()
    },
    formatHireType(value) {
      return hireType[value] || '未知'
    }

  }
}
</script>
